package com.sagittariusjin.android.serialportbecoroutine

import com.sagittariusjin.android.serialportbecoroutinelib.SerialPortFinder
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.sagittariusjin.android.serialportbecoroutinelib.bean.SerialBean
import com.sagittariusjin.android.serialportbecoroutinelib.client.SerialPortClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var serial =
            SerialPortFinder()
        val allDevices = serial.allDevices
        var textButton = findViewById<TextView>(R.id.textButton)
        var serial485 = SerialPortClient("/dev/ttyS7",9600);
        textButton.setOnClickListener {
            GlobalScope.launch(context = Dispatchers.IO) {
//                serial485.close()
                var backValue = serial485.putValues(SerialBean(content = byteArrayOf(0x98.toByte(),0x01,0x02)))
                println("${backValue?.content.toString()}")
            }

        }

        GlobalScope.launch(context = Dispatchers.IO) {
//            //延时一秒
//            delay(1000)
//            log("launch")
        allDevices.forEach {
//            print("${it}")

            var backValue = serial485.putValues(SerialBean(content = byteArrayOf(0x98.toByte(),0x01,0x02)))
            println("${backValue?.content.toString()}")
        }
        }

    }
}
